package com.study.demo_db_security_dynamic.config;

import com.study.demo_db_security_dynamic.bean.Menu;
import com.study.demo_db_security_dynamic.bean.Role;
import com.study.demo_db_security_dynamic.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName: MyFilter
 * @Description:
 * @author: WS
 * @date 2021/1/2
 * @Version: 1.0
 **/
@Component
public class MyFilter implements FilterInvocationSecurityMetadataSource {

    AntPathMatcher pathMatcher=new AntPathMatcher();
    @Autowired
    MenuService service;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<Menu> allMenus = service.getAllMenus();
        for (Menu menu : allMenus) {
            if(pathMatcher.match(menu.getPattern(),requestUrl)){
                List<Role> roles = menu.getRoles();
                String[] roleStr=new String[roles.size()];
                for (int i = 0; i <roles.size() ; i++) {
                    roleStr[i]="ROLE_"+roles.get(i).getName();
                }
                return SecurityConfig.createList(roleStr);
            }
        }
        return SecurityConfig.createList("ROLE_login");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
